/**
 * 中间件
 * 处理业务逻辑
 */
const path = require("path");
const fileUtils = require("../utils/file_utils")
module.exports = async (ctx, next) => {
  let isApiUrl = ctx.request.url;
  // url路径判断
  if (/\/(api).*?/.test(isApiUrl)){
    const url = ctx.request.url.replace('/api', '')
    // 发送服务端data目录的json文件
    let filePath = `../data${url}.json`
    filePath = path.join(__dirname,filePath)
    try {
      await fileUtils.getFileJsonData(filePath).then(res => {
        ctx.response.body = res
      })
    } catch (err) {
      const message = {
        message: 'readFile failed，Not file source',
        status: 404,
      }
      ctx.response.body = JSON.stringify(message)
    }
  } else {
    let message = {
      message: 'url location error',
      correctApi: 'baseUrl/api/parameter',
      status: 400
    }
    ctx.response.body = JSON.stringify(message)
  }

  await next();
}